﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Medusa.Service.Business.Core.Entities.JCPDTCPHJLC;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.StandardApprovalFlow.Dto;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform
{
    public class JCPDTCPHJLCService : BPMReportPlatformAppService, IJCPDTCPHJLCService
    {
        private readonly SqlSugarClient _db;
        private readonly SqlSugarClient _dbPlatform;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;

        public JCPDTCPHJLCService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp
            , IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        public async Task<PagedResultDto<GetJCPDTCPHJLCOutput>> GetAllAsync(GetJCPDTCPHJLCInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetJCPDTCPHJLCOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetJCPDTCPHJLCOutput>> ExportAsync(GetJCPDTCPHJLCInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }


        private ISugarQueryable<GetJCPDTCPHJLCOutput> GetQueryable(GetJCPDTCPHJLCInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>().Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }



            var listQueryable = _db.Queryable<JCPDTCPHJLCNoShippingDetail, JCPDTCPHJLCHeader, BusinessProcessesNew>(
                    (a, b, c) => new JoinQueryInfos(JoinType.Left, a.InstanceNumber == b.InstanceNumber, JoinType.Left, b.InstanceNumber == c.InstanceId))
                .WhereIF(!string.IsNullOrEmpty(input.InstanceNumber), (a, b, c) => b.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.IsQueryAll, (a, b, c) => b.AddUserId.Equals(currentUserId))
                .WhereIF(input.OrderStatus != null && input.OrderStatus.Length > 0,
                    (a, b, c) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), c.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), (a, b, c) => b.AddUserName.Contains(input.AddUserName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.SupplierName), (a, b, c) => b.SupplierName.Contains(input.SupplierName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    (a, b, c) => b.AddTime >= input.StartCreationTime && b.AddTime <= input.EndCreationTime)
                .Select((a, b, c) => new GetJCPDTCPHJLCOutput()
                {
                    InstanceNumber = b.InstanceNumber,
                    AniseCost = b.AniseCost,
                    ConcentrateCost = b.ConcentrateCost,
                    DemandDivision = b.DemandDivision,
                    FormulaCalculation = a.FormulaCalculation,
                    ManufacturingCosts = a.ManufacturingCosts,
                    OrderStatus = c.ProcessStatusName,
                    Package = a.Package,
                    ProcessStartTime = c.StartTime,
                    ProcessStartUserName = b.AddUserName,
                    ProductSpecifications = b.ProductSpecifications,
                    ProductTypeName = b.ProductTypeName,
                    RawMaterial = a.RawMaterial,
                    ScopeSupply = b.ScopeSupply,
                    SemiFinishedProductName = b.SemiFinishedProductName,
                    ShippingRequirements = b.ShippingRequirements,
                    SupplierName = b.SupplierName,
                    TraysAndWraps = a.TraysAndWraps,
                }).MergeTable().Distinct().OrderBy(ins => ins.ProcessStartTime, OrderByType.Desc);


            return listQueryable;
        }
    }
}